<script setup lang="ts" name="VehicleTrajectoryMap">
import { ElImageViewer } from 'element-plus';
import { loadAmap } from '/@/utils/mapLoad';
import { drawRoute } from '/@/utils/mapUtils';
import { vehicleTrajectoryMapKey } from './provider';
// import { drawMarker } from '/@/utils/mapUtils';
import dayjs from 'dayjs';
import MapLenged from './MapLenged.vue';
import GpsText from './GpsText.vue';
import CarDevice from './CarDevice.vue';

// import CameraLengedIcon from './icon/camera-lenged.png';
// import ProjectLengedIcon from './icon/project-lenged.png';
// import GarbageLengedIcon from './icon/garbage-lenged.png';
// import LoadLengedIcon from './icon/load-lenged.png';
// import UnloadLengedIcon from './icon/unload-lenged.png';
import CameraMarkerIcon from './icon/camera.png';
// import ProjectMarkerIcon from './icon/project.png';
import GarbageMarkerIcon from './icon/garbage.png';
import LoadMarkerIcon from './icon/load.png';
import UnloadMarkerIcon from './icon/unload.png';
// 新图标
import MapCar from './icon/map-car.png';
import MapStop from './icon/stop.png';
import MapStopLen from './icon/stop-lenged.png';
import MapWork from './icon/work.png';
import MapWorkLen from './icon/work_lenged.png';
import MapTrajectory from './icon/trajectory.png';
import MapBayonet from './icon/bayonet.png';
// import MapSpeed from './icon/speed.png';
import biaozhunIcon from '/@/assets/biaozhun.png';
import weixinIcon from '/@/assets/weixin.png';
/**
 * 车辆轨迹地图
 * 图列
 * 聚合点
 * 	不同类型的点弹窗
 * 点标记
 *  轨迹回放
 * 轨迹
 * 摄像头
 * 	抓拍 视频回放
 */

interface PointType {
	lnglat: number[];
}
const props = withDefaults(
	defineProps<{
		kuponoId?: string;
		date?: string[];
		pointData: {
			camera: PointType[]; // 摄像头
			project: PointType[]; // 工地
			garbage: PointType[]; // 消纳
			load: PointType[]; // 装在点
			unload: PointType[]; // 卸载点
			stay: PointType[]; // 停留点位
			bayonet: PointType[]; // 卡口数据
		};
		pathData: Array<{
			lng: number;
			lat: number;
			time: string;
		}>;
		timePeriod?: string[]; // 改为可选
		carInfo?: {
			// 改为可选
			hphm?: string; // 改为可选
			// 其他属性...
		};
		deviceList?: any[]; // 改为可选
	}>(),
	{
		// 提供默认值
		timePeriod: () => ['', ''],
		carInfo: () => ({ hphm: '' }),
		deviceList: () => [],
	},
);

const emits = defineEmits<{
	'camera-marker-click': [data: any];
}>();

provide(vehicleTrajectoryMapKey, {
	startCarMarkerAnimation,
	pauseCarMarkerAnimation,
	resumeCarMarkerAnimation,
	setCarMovingEvent,
	setCarMovealongEvent,
	setCarMarkerMoveCurrentPosition,
	getCurrentPosition: () => carMarkerMoveCurrentPosition.value,
});

let map: any;

onMounted(() => {
	initMap();
});

onUnmounted(() => {
	if (map) map.destroy();
});

// 事件类型
enum EventType {
	Camera = 'camera',
	Project = 'project',
	Garbage = 'garbage',
	Load = 'load',
	Unload = 'unload',
	Stay = 'stay',
	Path = 'path',
	Bayonet = 'bayonet',
}

// 地图初始化
// 车辆marker
let carMarker: any;
// 移动到第几个点
const carMarkerMoveCurrentPosition = ref(0);
// 车辆marker移动事件注入
const carMoveEvent = ref<{
	moving: (
		e: any,
		data: {
			data: {
				lng: number;
				lat: number;
				time: string;
			};
			index: number;
		},
	) => void;
	movealong: () => void;
}>({
	moving: () => {},
	movealong: () => {},
});

// 滑块设置当前播放位置
function setCarMarkerMoveCurrentPosition(time: string) {
	const diffArr: number[] = [];
	props.pathData.forEach((item) => {
		diffArr.push(Math.abs(dayjs(time).diff(dayjs(item.time), 'milliseconds')));
	});

	const index = diffArr.findIndex((item) => item === Math.min(...diffArr));
	carMarkerMoveCurrentPosition.value = index === -1 ? 0 : index;

	// 设置车辆位置
	carMarker.setPosition([
		props.pathData[carMarkerMoveCurrentPosition.value].lng,
		props.pathData[carMarkerMoveCurrentPosition.value].lat,
	]);

	// 停止当前动画
	carMarker.stopMove();
}

// 设置car移动中监听位置
function setCarMovingEvent(cb: (e: any) => void) {
	carMoveEvent.value.moving = cb;
	console.log(carMoveEvent.value.moving, 999999);
}

// 设置car移动结束监听位置
function setCarMovealongEvent(cb: () => void) {
	carMoveEvent.value.movealong = cb;
}

watch(
	() => [props.pathData, props.pointData],
	() => {
		initMap();
	},
);
const mapMode = ref('normal'); //地图模式

async function initMap() {
	try {
		await loadAmap();
		if (!map) {
			map = new window.AMap.Map('kupono-map-container', {
				zoom: 12,
				defaultType: 'normal',
				layers: [
					new AMap.createDefaultLayer({
						zooms: [3, 20],
						visible: true,
						opacity: 1,
						zIndex: 0,
						customStyle: {
							building: {
								visible: true,
								fillColor: '#FFFFFF',
								strokeColor: '#FFFFFF',
							},
							road: {
								visible: false,
							},
							text: {
								visible: false,
							},
						},
					}),
				], // 默认标准图层
			});
		}

		map.clearMap();

		// 绘制路线
		if (props.pathData.length > 0) {
			drawRoute(
				map,
				props.pathData.map((item) => [item.lng, item.lat]),
				'#437AFF',
				true,
				false,
			);

			// 添加起点
			addMarker({
				position: [props.pathData[0].lng, props.pathData[0].lat],
				offset: new window.AMap.Pixel(-8, -8),
				content:
					'<div style="width: 16px;height: 16px;border-radius: 9px;background: #fff;border: 6px solid var(--el-color-primary);"></div>',
			});
			// 添加终点
			addMarker({
				position: [
					props.pathData[props.pathData.length - 1].lng,
					props.pathData[props.pathData.length - 1].lat,
				],
				offset: new window.AMap.Pixel(-8, -8),
				content:
					'<div style="width: 16px;height: 16px;border-radius: 9px;background: #fff;border: 6px solid var(--el-color-primary);"></div>',
			});

			// 绘制车辆
			carMarker = addMarker({
				position: [props.pathData[0].lng, props.pathData[0].lat],
				offset: new window.AMap.Pixel(-40, -30),
				content: markerContent(),
			});

			// marker移动监听
			carMarker.on('moving', function (e: any) {
				// 记录移动到第几个点
				carMarkerMoveCurrentPosition.value = e.passedPath.length;
				carMoveEvent.value.moving(e, {
					data: props.pathData[carMarkerMoveCurrentPosition.value - 1],
					index: carMarkerMoveCurrentPosition.value,
				});
			});

			// marker移动结束监听
			carMarker.on('movealong', function () {
				console.log('移动结束');
				carMarker.stopMove();
				carMarkerMoveCurrentPosition.value = 0;
				carMoveEvent.value.movealong();
			});
		}

		// 绘制聚合点
		drawMarkerCluster();

		//地图切换
		// 添加自定义地图切换控件
		const mapTypeContainer = document.createElement('div');
		mapTypeContainer.className = 'map-type-switch';
		mapTypeContainer.id = 'mapTypeSwitch';
		mapTypeContainer.style.display = 'block';
		mapTypeContainer.innerHTML = `
			<div class="map-type-options">
				<div class="map-type-option ${mapMode.value === 'normal' ? 'active' : ''}"
					data-type="标准地图">
					<img src="${biaozhunIcon}" alt="标准地图" class="map-icon" />
				</div>
				<div class="map-type-option ${mapMode.value === 'satellite' ? 'active' : ''}"
					data-type="卫星地图">
					<img src="${weixinIcon}" alt="卫星地图" class="map-icon" />
				</div>
			</div>
		`;

		// 修改地图类型切换的处理
		mapTypeContainer.addEventListener('click', (e) => {
			const target = e.target.closest('.map-type-option');
			if (target) {
				const type = target.getAttribute('data-type');
				mapMode.value = type === '标准地图' ? 'normal' : 'satellite';

				// 更新按钮状态
				mapTypeContainer.querySelectorAll('.map-type-option').forEach((el) => {
					el.classList.toggle('active', el.getAttribute('data-type') === type);
				});

				// 切换地图图层
				// 切换地图图层
				if (mapMode.value === 'satellite') {
					// 设置卫星图层
					const satelliteLayer = new AMap.TileLayer.Satellite();
					const roadNetLayer = new AMap.TileLayer.RoadNet();
					map.setLayers([satelliteLayer, roadNetLayer]);
				} else {
					// 获取当前所有图层
					const layers = map.getLayers();

					// 移除所有现有图层，特别是路网图层
					layers.forEach((layer: any) => {
						if (layer.CLASS_NAME != 'AMap.VectorLayer') {
							map.remove(layer);
						}
					});

					// 恢复标准地图
					const standardLayer = new AMap.createDefaultLayer({
						zooms: [3, 20],
						visible: true,
						opacity: 1,
						zIndex: 0,
						customStyle: {
							building: {
								visible: true,
								fillColor: '#FFFFFF',
								strokeColor: '#FFFFFF',
							},
							road: {
								visible: false,
							},
							text: {
								visible: false,
							},
						},
					});
					map.setLayers([standardLayer]);
				}
			}
		});

		map.getContainer().appendChild(mapTypeContainer);

		map.on('click', () => {
			infoWindowclose();
		});

		map.setFitView();
	} catch (err) {
		console.error(err);
	}
}

/* ------------------ 绘制车辆 ------------------------- */
function addMarker(options: {
	position: number[];
	offset: any;
	content?: string;
}) {
	if (!map) return;

	const marker = new window.AMap.Marker(options);
	map.add(marker);
	return marker;
}

function markerContent() {
	return `
    <div class="box">
      <div class="big"></div>
      <div class="small"></div>
      <div class="car">
        <img src="${MapCar}" />
      </div>
    </div>`;
}

function startCarMarkerAnimation(
	speed: number,
	init?: boolean,
	customPath?: any[],
) {
	if (init) {
		carMarkerMoveCurrentPosition.value = 0;
	}

	// 停止当前动画
	carMarker.stopMove();

	const pathArr =
		customPath ||
		props.pathData.map((item) => ({
			position: [item.lng, item.lat],
			...item,
		}));

	carMarker.moveAlong(pathArr, {
		duration: speed,
		autoRotation: true,
	});
}

function pauseCarMarkerAnimation() {
	carMarker.pauseMove();
}
function resumeCarMarkerAnimation() {
	carMarker.resumeMove();
}

/* ------------------ 点聚合 -------------------------- */
let markerClusterCamera: any;
let markerClusterProject: any;
let markerClusterGarbage: any;
let markerClusterLoad: any;
let markerClusterUnload: any;
let markerClusterStay: any;
let markerClusterPath: any;
let marketClusterBayonet: any;
let cameraPoint: PointType[];
let projectPoint: PointType[];
let garbagePoint: PointType[];
let loadPoint: PointType[];
let unloadPoint: PointType[];
let stayPoint: PointType[];
let trajectPoint: PointType[];
let bayonetPoint: PointType[];
function drawMarkerCluster() {
	const cameraLenged = lengeds.value.find((l) => l.type === EventType.Camera);
	const projectLenged = lengeds.value.find((l) => l.type === EventType.Project);
	const garbageLenged = lengeds.value.find((l) => l.type === EventType.Garbage);
	const loadLenged = lengeds.value.find((l) => l.type === EventType.Load);
	const unloadLenged = lengeds.value.find((l) => l.type === EventType.Unload);
	const stayLenged = lengeds.value.find((l) => l.type === EventType.Stay);
	const PathLenged = lengeds.value.find((l) => l.type === EventType.Path);
	const bayonetLenged = lengeds.value.find((l) => l.type === EventType.Bayonet);
	// 摄像头
	if (cameraLenged && cameraLenged.selected) {
		cameraPoint = props.pointData.camera.map((item) => ({
			...item,
			type: EventType.Camera,
			icon: CameraMarkerIcon,
		}));
	} else {
		cameraPoint = [];
	}
	if (!markerClusterCamera) {
		markerClusterCamera = new window.AMap.MarkerCluster(map, cameraPoint, {
			gridSize: 60, // 聚合网格像素大小
			renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
			renderMarker: _renderMarker, // 自定义非聚合点样式
		});
		markerClusterCamera.on('click', markerClusterClickHandler);
	} else {
		markerClusterCamera.setData(cameraPoint);
	}

	// 工地
	if (projectLenged && projectLenged.selected) {
		projectPoint = props.pointData.project.map((item) => ({
			...item,
			type: EventType.Project,
			icon: MapWork,
		}));
	} else {
		projectPoint = [];
	}
	if (!markerClusterProject) {
		markerClusterProject = new window.AMap.MarkerCluster(map, projectPoint, {
			gridSize: 60, // 聚合网格像素大小
			renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
			renderMarker: _renderMarker, // 自定义非聚合点样式
		});
		markerClusterProject.on('click', markerClusterClickHandler);
	} else {
		markerClusterProject.setData(projectPoint);
	}

	// 消纳
	if (garbageLenged && garbageLenged.selected) {
		garbagePoint = props.pointData.garbage.map((item) => ({
			...item,
			type: EventType.Garbage,
			icon: GarbageMarkerIcon,
		}));
	} else {
		garbagePoint = [];
	}
	if (!markerClusterGarbage) {
		markerClusterGarbage = new window.AMap.MarkerCluster(map, garbagePoint, {
			gridSize: 60, // 聚合网格像素大小
			renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
			renderMarker: _renderMarker, // 自定义非聚合点样式
		});
		markerClusterGarbage.on('click', markerClusterClickHandler);
	} else {
		markerClusterGarbage.setData(garbagePoint);
	}

	// 装载点
	if (loadLenged && loadLenged.selected) {
		loadPoint = props.pointData.load.map((item) => ({
			...item,
			type: EventType.Load,
			icon: LoadMarkerIcon,
		}));
	} else {
		loadPoint = [];
	}
	if (!markerClusterLoad) {
		markerClusterLoad = new window.AMap.MarkerCluster(map, loadPoint, {
			gridSize: 60, // 聚合网格像素大小
			renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
			renderMarker: _renderMarker, // 自定义非聚合点样式
		});
		markerClusterLoad.on('click', markerClusterClickHandler);
	} else {
		markerClusterLoad.setData(loadPoint);
	}

	// 卸载点
	if (unloadLenged && unloadLenged.selected) {
		unloadPoint = props.pointData.unload.map((item) => ({
			...item,
			type: EventType.Unload,
			icon: UnloadMarkerIcon,
		}));
	} else {
		unloadPoint = [];
	}
	if (!markerClusterUnload) {
		markerClusterUnload = new window.AMap.MarkerCluster(map, unloadPoint, {
			gridSize: 60, // 聚合网格像素大小
			renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
			renderMarker: _renderMarker, // 自定义非聚合点样式
		});
		markerClusterUnload.on('click', markerClusterClickHandler);
	} else {
		markerClusterUnload.setData(unloadPoint);
	}
	// 轨迹点 markerClusterPath
	if (PathLenged && PathLenged.selected) {
		trajectPoint = props.pathData.map((item) => ({
			...item,
			type: EventType.Path,
			icon: MapTrajectory,
		}));
	} else {
		trajectPoint = [];
	}
	if (!markerClusterPath) {
		markerClusterPath = new window.AMap.MarkerCluster(map, trajectPoint, {
			gridSize: 10, // 聚合网格像素大小
			renderClusterMarker: _renderClusterMarker2, // 自定义聚合点样式
			renderMarker: _renderMarker2, // 自定义非聚合点样式
		});
		markerClusterPath.on('click', markerClusterClickHandler);
	} else {
		markerClusterPath.setData(trajectPoint);
	}
	// 停留点
	if (stayLenged && stayLenged.selected) {
		stayPoint = props.pointData.stay.map((item) => ({
			...item,
			type: EventType.Stay,
			icon: MapStop,
		}));
	} else {
		stayPoint = [];
	}

	if (!markerClusterStay) {
		markerClusterStay = new window.AMap.MarkerCluster(map, stayPoint, {
			gridSize: 60, // 聚合网格像素大小
			renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
			renderMarker: _renderMarker, // 自定义非聚合点样式
		});
		markerClusterStay.on('click', markerClusterClickHandler);
	} else {
		markerClusterStay.setData(stayPoint);
	}
	// 卡口
	if (bayonetLenged && bayonetLenged.selected) {
		//
		bayonetPoint = props.pointData.bayonet.map((item) => ({
			...item,
			type: EventType.Bayonet,
			icon: MapBayonet,
		}));
	} else {
		bayonetPoint = [];
	}
	if (!marketClusterBayonet) {
		marketClusterBayonet = new window.AMap.MarkerCluster(map, bayonetPoint, {
			gridSize: 60, // 聚合网格像素大小
			renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
			renderMarker: _renderMarker, // 自定义非聚合点样式
		});
		marketClusterBayonet.on('click', markerClusterClickHandler);
	} else {
		marketClusterBayonet.setData(bayonetPoint);
	}
	function markerClusterClickHandler(e: any) {
		if (e.clusterData.length <= 1) return;
		map.setZoom(20);
		map.setCenter([e.clusterData[0].lng, e.clusterData[0].lat]);
	}
}

function _renderClusterMarker(context: any) {
	// 聚合中点个数
	const clusterCount = context.count;
	const div = document.createElement('div');
	div.style.position = 'relative';

	const img = document.createElement('img');
	img.src = context.clusterData[0].icon;
	img.style.height = '57px';
	img.style.width = '50px';
	div.appendChild(img);

	const badge = document.createElement('div');
	badge.style.display = 'flex';
	badge.style.alignItems = 'center';
	badge.style.justifyContent = 'center';
	badge.style.width = '22px';
	badge.style.height = '14px';
	badge.style.backgroundColor = '#FF543D';
	badge.style.color = '#fff';
	badge.style.borderRadius = '7px';
	badge.style.fontSize = '12px';
	badge.style.border = '1px solid #FFFFFF';
	badge.style.position = 'absolute';
	badge.style.top = '0';
	badge.style.right = '0';
	badge.style.lineHeight = '1';
	badge.innerHTML = clusterCount;
	div.appendChild(badge);

	context.marker.setOffset(new window.AMap.Pixel(-57 / 2, -57 / 2));
	context.marker.setContent(div);
}
function _renderClusterMarker2(context: any) {
	// 聚合中点个数
	const clusterCount = context.count;
	const div = document.createElement('div');
	div.style.position = 'relative';

	const img = document.createElement('img');
	img.src = context.clusterData[0].icon;
	img.style.height = '15px';
	img.style.width = '15px';
	div.appendChild(img);

	const badge = document.createElement('div');
	badge.style.display = 'flex';
	badge.style.alignItems = 'center';
	badge.style.justifyContent = 'center';
	badge.style.width = '22px';
	badge.style.height = '14px';
	badge.style.backgroundColor = '#FF543D';
	badge.style.color = '#fff';
	badge.style.borderRadius = '7px';
	badge.style.fontSize = '12px';
	badge.style.border = '1px solid #FFFFFF';
	badge.style.position = 'absolute';
	badge.style.top = '0';
	badge.style.right = '0';
	badge.style.lineHeight = '1';
	badge.innerHTML = clusterCount;
	div.appendChild(badge);

	context.marker.setOffset(new window.AMap.Pixel(-10, -10));
	context.marker.setContent(div);
}
function _renderMarker(context: any) {
	const markerInfo = context.data[0];
	const content = document.createElement('img');
	content.src = context.data[0].icon;
	content.style.height = '57px';
	content.style.width = '50px';

	context.marker.setOffset(new window.AMap.Pixel(0, 0));
	context.marker.setContent(content);
	context.marker.on('click', () => {
		if (markerInfo.type === 'bayonet') {
			markerClusterBayonetClick(markerInfo);
		} else {
			markerClick(markerInfo);
		}
	});
}
function _renderMarker2(context: any) {
	const content = document.createElement('img');
	content.src = context.data[0].icon;
	content.style.height = '15px';
	content.style.width = '15px';

	context.marker.setOffset(new window.AMap.Pixel(-10, -10));
	context.marker.setContent(content);
	context.marker.on('click', () => markerClick(context.data[0]));
}

/* ------------------ 信息窗体 ------------------------- */
let InfoWindow: any;
function markerClick(data: any) {
	if (data.type === EventType.Camera) {
		emits('camera-marker-click', data);
		return;
	}

	let title = '';
	let bgColor = '';
	let subTitle = '';
	let element = '';
	if (data.type === EventType.Project) {
		title = '项目';
		bgColor = '#FF993B';
		element = `<div class="text-[17px] text-[#3e3e3e] leading-none mb-2">${data.name}</div>
		<div class="text-xs text-[#979797]">${data.address}</div>`;
	}
	if (data.type === EventType.Garbage) {
		title = '末端消纳';
		bgColor = '#A94FC9';
		subTitle = '临时消纳点';
		element = `<div class="text-[17px] text-[#3e3e3e] leading-none mb-2">${data.name}</div>
		<div class="text-xs text-[#979797]">${data.address}</div>`;
	}
	if (data.type === EventType.Load) {
		title = '装载点';
		bgColor = 'var(--el-color-primary)';
		element = `<div class="text-xs mb-2"><span class="text-[#979797]">开始装载：</span>${data.startTime}</div>
		<div class="text-xs"><span class="text-[#979797]">结束装载：</span>${data.endTime}</div>
		<div class="text-xs text-[#979797]">重量变化：<span class="text-[#FF543D] text-4xl mr-1">+${data.weight}</span>方</div>`;
	}
	if (data.type === EventType.Unload) {
		title = '卸载点';
		bgColor = '#9C5038';
		element = `<div class="text-xs mb-2"><span class="text-[#979797]">开始装载：</span>${data.startTime}</div>
		<div class="text-xs"><span class="text-[#979797]">结束装载：</span>${data.endTime}</div>
		<div class="text-xs text-[#979797]">重量变化：<span class="text-[#14BD6C] text-4xl mr-1">${data.weight}</span>方</div>`;
	}

	if (data.type === EventType.Stay) {
		title = '停留点';
		bgColor = '#9C5038';
		element = `<div class="text-xs mb-2"><span class="text-[#979797]">开始时间：</span>${data.startTime}</div>
		<div class="text-xs"><span class="text-[#979797]">结束时间：</span>${data.endTime}</div>
		<div class="text-xs text-[#979797]">停留时长：<span class="text-[#14BD6C] text-4xl mr-1">${data.diffSeconds}</span>秒</div>`;
	}

	if (!InfoWindow) {
		InfoWindow = new window.AMap.InfoWindow({
			isCustom: true, //使用自定义窗体
			content: _renderInfoWindow(title, bgColor, element, subTitle),
			offset: new window.AMap.Pixel(25, 5),
		});
	}
	InfoWindow.setContent(_renderInfoWindow(title, bgColor, element, subTitle));
	InfoWindow.open(map, [data.lnglat.lng, data.lnglat.lat]);

	map.setCenter([data.lnglat.lng, data.lnglat.lat]);
}
function markerClusterBayonetClick(checkpoint: any) {
	// 准备数据
	let currentIndex = 0;
	const images = checkpoint.bayonetImageUrlArr.map(
		(item) => item.bayonetImageUrl,
	);

	// 创建信息窗体内容
	const infoContent = document.createElement('div');
	infoContent.className = 'checkpoint-info-window';

	// 标题部分
	const title = document.createElement('div');
	title.className = 'info-title';
	title.innerHTML = `
				<div class="title-content">
					
					<div class="address"><span class="label">地址：</span> ${checkpoint.deviceAddress || '卡口监控点'}</div>
					<div class="time"><span class="label">拍摄时间：</span> ${checkpoint.bayonetImageUrlArr[currentIndex]?.snapTime || '--'}</div>
						</div>
					`;
	infoContent.appendChild(title);

	// 图片容器
	const imageContainer = document.createElement('div');
	imageContainer.className = 'image-container';

	// 图片计数器
	const imageCounter = document.createElement('div');
	imageCounter.className = 'image-counter';
	imageCounter.innerHTML = `${currentIndex + 1}/${images.length}`;
	imageContainer.appendChild(imageCounter);

	// 图片展示区
	const imageWrapper = document.createElement('div');
	imageWrapper.className = 'image-wrapper';
	const image = document.createElement('img');
	image.src = images[currentIndex];

	// 添加图片点击预览功能
	image.addEventListener('click', (e) => {
		e.stopPropagation();

		// 创建预览组件的容器
		const viewerContainer = document.createElement('div');
		document.body.appendChild(viewerContainer);

		// 创建预览组件实例
		const app = createApp({
			setup() {
				const show = ref(true);

				const onClose = () => {
					show.value = false;
					setTimeout(() => {
						app.unmount();
						document.body.removeChild(viewerContainer);
					}, 200);
				};

				return () =>
					show.value
						? h(ElImageViewer, {
								urlList: images,
								initialIndex: currentIndex,
								onClose,
								zIndex: 3000,
							})
						: null;
			},
		});

		app.mount(viewerContainer);
	});

	imageWrapper.appendChild(image);

	// 定义更新函数
	const updateCounter = () => {
		imageCounter.innerHTML = `${currentIndex + 1}/${images.length}`;
	};

	const updateTimeInfo = () => {
		const currentImage = checkpoint.bayonetImageUrlArr[currentIndex];
		title.querySelector('.time').textContent =
			`拍摄时间：${currentImage?.snapTime || '--'}`;
	};

	// 创建导航按钮
	const prevBtn = document.createElement('div');
	prevBtn.className = 'nav-btn prev-btn';
	prevBtn.innerHTML = '←';

	const nextBtn = document.createElement('div');
	nextBtn.className = 'nav-btn next-btn';
	nextBtn.innerHTML = '→';

	// 添加按钮事件
	prevBtn.addEventListener('click', (e) => {
		e.stopPropagation();
		currentIndex = (currentIndex - 1 + images.length) % images.length;
		image.src = images[currentIndex];
		updateTimeInfo();
		updateCounter();
	});

	nextBtn.addEventListener('click', (e) => {
		e.stopPropagation();
		currentIndex = (currentIndex + 1) % images.length;
		image.src = images[currentIndex];
		updateTimeInfo();
		updateCounter();
	});

	// 组装容器
	imageContainer.appendChild(prevBtn);
	imageContainer.appendChild(imageWrapper);
	imageContainer.appendChild(nextBtn);
	infoContent.appendChild(imageContainer);

	// 添加关闭按钮
	const closeBtn = document.createElement('div');
	closeBtn.className = 'close-btn';
	closeBtn.innerHTML = '关闭';
	closeBtn.addEventListener('click', (e) => {
		e.stopPropagation();
		infoWindowclose(); // 调用关闭信息窗体的方法
	});
	infoContent.appendChild(closeBtn);

	// 创建信息窗体
	createInfoWindow({
		content: infoContent,
		offset: new AMap.Pixel(0, -20),
		position: [checkpoint.lng, checkpoint.lat],
		closeWhenClickMap: true,
		type: true,
		moveToCenter: false,
	});
}
function createInfoWindow({
	content = '',
	offset = [0, 0],
	position = [0, 0],
	closeWhenClickMap = true,
	type = true,
	moveToCenter = true, // 添加控制是否移动到中心点的参数
}) {
	infoWindowclose();
	nextTick(() => {
		InfoWindow = new window.AMap.InfoWindow({
			isCustom: true, //使用自定义窗体
			closeWhenClickMap,
			offset,
			content,
		});
		nextTick(() => {
			InfoWindow.open(map, position);
			// 根据 moveToCenter 参数决定是否移动地图中心点
			if (moveToCenter && type != MapMarkerType.Stay) {
				map.setCenter(position);
			} else {
				// 保持当前视图
				const currentCenter = map.getCenter();
				const currentZoom = map.getZoom();
				setTimeout(() => {
					map.setZoomAndCenter(currentZoom, currentCenter);
				}, 0);
			}
		});
	});
}
function _renderInfoWindow(
	title: string,
	bgColor: string,
	element: string,
	subTitle?: string,
) {
	return `<div class="info-window flex flex-col items-center justify-center relative">
			<div class="info-window-container flex-1 w-full bg-white">
				<div class="info-window-title shrink-0 px-3 flex items-center justify-between text-xs text-white" style="background-color: ${bgColor}">
					<span>${title}</span>
					<span>${subTitle}</span>
				</div>
				<div class="info-window-content flex-1 p-3 flex flex-col">${element}</div>
			</div>
			<div class="h-[14px] shrink-0"></div>
			<div class="triangle-icon absolute"></div>
		</div>`;
}

function infoWindowclose() {
	InfoWindow?.close();
}

/*------------------ 图列 ----------------------*/
const lengeds = ref([
	// {
	// 	name: '摄像头',
	// 	type: EventType.Camera,
	// 	selected: true,
	// 	icon: CameraLengedIcon,
	// },

	// {
	// 	name: '末端消纳',
	// 	type: EventType.Garbage,
	// 	selected: true,
	// 	icon: GarbageLengedIcon,
	// },
	// {
	// 	name: '装货事件',
	// 	type: EventType.Load,
	// 	selected: true,
	// 	icon: LoadLengedIcon,
	// },
	// {
	// 	name: '卸货事件',
	// 	type: EventType.Unload,
	// 	selected: true,
	// 	icon: UnloadLengedIcon,
	// },
	{
		name: '轨迹点',
		type: EventType.Path,
		selected: true,
		icon: MapTrajectory,
	},
	{
		name: '卡口',
		type: EventType.Bayonet,
		selected: true,
		icon: MapBayonet,
	},
	{
		name: '停靠点',
		type: EventType.Stay,
		selected: true,
		icon: MapStopLen,
	},
	{
		name: '工地',
		type: EventType.Project,
		selected: true,
		icon: MapWorkLen,
	},
	// {
	// 	name: '超速点',
	// 	type: EventType.Project,
	// 	selected: true,
	// 	icon: MapSpeed,
	// },
]);

function lengedChange(data: any) {
	const lenged = lengeds.value[data.index];
	console.log(data, 'data', lenged);
	lenged.selected = data.selected;
	if (lenged.type === EventType.Camera) {
		markerClusterCamera.setData(lenged.selected ? cameraPoint : []);
	}
	if (lenged.type === EventType.Project) {
		markerClusterProject.setData(lenged.selected ? projectPoint : []);
	}
	if (lenged.type === EventType.Garbage) {
		markerClusterGarbage.setData(lenged.selected ? garbagePoint : []);
	}
	if (lenged.type === EventType.Load) {
		markerClusterLoad.setData(lenged.selected ? loadPoint : []);
	}
	if (lenged.type === EventType.Unload) {
		markerClusterUnload.setData(lenged.selected ? unloadPoint : []);
	}
	if (lenged.type === EventType.Stay) {
		markerClusterStay.setData(lenged.selected ? stayPoint : []);
	}
	if (lenged.type === EventType.Path) {
		markerClusterPath.setData(lenged.selected ? trajectPoint : []);
	}
	if (lenged.type === EventType.Bayonet) {
		markerClusterPath.setData(lenged.selected ? bayonetPoint : []);
	}
	//
	infoWindowclose();
}

// 添加在线率状态
const onlineRate = ref(0);

// 处理在线率更新

// 确保 carInfo 始终有值
const safeCarInfo = computed(() => {
	return props.carInfo || { hphm: '' };
});

// 重置图例选中状态，全部设为选中
function resetLegendsSelection() {
	lengeds.value.forEach((legend) => {
		legend.selected = true;
	});

	// 重新绘制所有点位
	drawMarkerCluster();
}

// 暴露方法给父组件使用
defineExpose({
	resetLegendsSelection,
});
</script>

<template>
	<div class="vehicle-trajectory relative">
		<div id="kupono-map-container"></div>

		<MapLenged :lengeds="lengeds" @lenged-change="lengedChange" />
		<GpsText
			v-if="
				props.timePeriod &&
				props.timePeriod.length === 2 &&
				props.carInfo &&
				props.carInfo.hphm
			"
			:timePeriod="props.timePeriod"
			:hphm="props.carInfo.hphm"
		/>
		<CarDevice
			v-if="props.carInfo"
			:show="showCarInfo"
			:carInfo="{ ...safeCarInfo, onlineRate: onlineRate }"
			:deviceList="{
				camera: Array.isArray(props.deviceList) ? props.deviceList : [],
			}"
		/>
		<slot />
	</div>
</template>

<style lang="scss" scoped>
#kupono-map-container {
	height: 460px;
}

:deep(.box) {
	position: relative;
	width: 75px;
	height: 75px;
	display: flex;
	align-items: center;
	justify-content: center;

	.big {
		position: absolute;
		width: 75px;
		height: 75px;
		background: linear-gradient(
			224deg,
			rgba(67, 122, 255, 0.3) 56%,
			#437aff 100%
		);
		opacity: 0.8;
		animation: zoom linear 1.2s infinite;
		animation-delay: 0.1 s;
		border-radius: 75px;
	}

	.small {
		position: absolute;
		width: 47px;
		height: 47px;
		border-radius: 47px;
		background: linear-gradient(
			224deg,
			rgba(67, 122, 255, 0.3) 56%,
			#437aff 100%
		);
		opacity: 0.6;
		animation: zoom linear 1.2s infinite;
	}

	.car {
		width: 16px;
		height: 40px;

		img {
			width: inherit;
			height: inherit;
		}
	}

	@keyframes zoom {
		0% {
			transform: scale(0.5);
			opacity: 0.8;
		}

		100% {
			transform: scale(1);
			opacity: 0.1;
		}
	}
}

:deep(.info-window) {
	width: 218px;
	height: 146px;

	.info-window-container {
		box-shadow: 0px 4px 18px 0px rgba(0, 0, 0, 0.09);
		border-radius: 4px;
	}

	.info-window-title {
		width: 100%;
		height: 35px;
		border-radius: 4px;
	}

	.triangle-icon {
		border: 10px solid transparent;
		border-top-color: #ffffff;
		bottom: -6px;
	}
}

.mask-btn {
	width: 119px;
	height: 36px;
	background: rgba(0, 0, 0, 0.51);
	border-radius: 4px;
	border: 1px solid #ffffff;
}

:deep(.checkpoint-marker-container) {
	.marker-content {
		position: relative;
		display: inline-block;

		.marker-circle {
			width: 36px;
			height: 36px;
			background: #fff;
			border-radius: 50%;
			box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
			padding: 2px;
			transition: all 0.3s ease;
			display: flex;
			align-items: center;
			justify-content: center;

			img {
				width: 100%;
				height: 100%;
				object-fit: contain;
				border-radius: 50%;
			}

			&:hover {
				transform: scale(1.1);
				box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
			}
		}

		.marker-badge {
			position: absolute;
			top: -8px;
			right: -8px;
			min-width: 16px;
			height: 16px;
			padding: 0 4px;
			background: linear-gradient(135deg, #ff4d4d, #f56c6c);
			color: #fff;
			border-radius: 8px;
			font-size: 12px;
			line-height: 16px;
			text-align: center;
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
			font-weight: 500;
			border: 1px solid rgba(255, 255, 255, 0.6);
		}
	}
}

:deep(.checkpoint-info-window) {
	padding: 8px;
	background: white;
	border-radius: 4px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
	width: 280px;

	.info-title {
		font-size: 14px;
		font-weight: 500;
		color: #333;
		margin-bottom: 10px;
		display: flex;
		flex-direction: column;
		gap: 4px;

		.title-content {
			color: #333;
			line-height: 1.5;
			word-break: break-all;
			.label {
				color: #666;
				line-height: 1.5;
				word-break: break-all;
			}
		}
	}

	.image-container {
		position: relative;
		width: 100%;
		/* height: 180px; */
		overflow: hidden;
		min-height: 130px;
		background: #f5f5f5;
		border-radius: 2px;
		margin-bottom: 8px;
		padding: 4px;

		.image-wrapper {
			width: 100%;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;

			img {
				max-width: 100%;
				max-height: 100%;
				width: 100%;
				height: 100%;
				object-fit: contain;
			}
		}

		.image-counter {
			position: absolute;
			bottom: 15px;
			right: 8px;
			background: rgba(0, 0, 0, 0.5);
			color: white;
			padding: 2px 8px;
			border-radius: 12px;
			font-size: 12px;
			z-index: 2;
		}

		.nav-btn {
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
			background: rgba(0, 0, 0, 0.3);
			color: white;
			width: 24px;
			height: 24px;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 14px;
			cursor: pointer;
			opacity: 0;
			transition: opacity 0.3s;
			z-index: 2;

			&.prev-btn {
				left: 8px;
			}

			&.next-btn {
				right: 8px;
			}

			&:hover {
				background: rgba(0, 0, 0, 0.5);
			}
		}

		&:hover {
			.nav-btn {
				opacity: 1;
			}
		}
	}

	.info-footer {
		margin-top: 12px;
		padding-top: 12px;
		border-top: 1px solid #eee;
		font-size: 14px;
		color: #666;

		.info-item {
			display: flex;
			align-items: center;
			margin-bottom: 4px;
			font-size: 12px;

			.label {
				color: #999;
				margin-right: 8px;
			}

			&:last-child {
				margin-bottom: 0;
			}
		}
	}

	.close-btn {
		/* width: 150px; */
		width: 180px;
		height: 36px;
		background: #edf5ff;
		line-height: 36px;
		border-radius: 18px;
		text-align: center;

		color: #0076ff;
		font-size: 16px;
		cursor: pointer;
		/* border-radius: 0; */
		/* border-top: 1px solid #eee; */
		transition: all 0.3s;
		margin-left: 45px;
		/* width: calc(100% + 16px); */

		&:hover {
			background: #f5f5f5;
		}
	}
}
.checkpoint-info-window {
	background: white;
	border-radius: 8px;
	overflow: hidden;
	width: 300px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

	.info-title {
		padding: 12px 16px;
		border-bottom: 1px solid #eee;

		.title-content {
			display: flex;
			flex-direction: column;
			gap: 8px;

			.time {
				font-size: 12px;
				color: #666;
			}
			.address {
				font-size: 12px;
				color: #666;
			}
		}
	}

	.image-container {
		position: relative;
		width: 100%;
		height: 200px;
		background: #f5f5f5;

		.image-wrapper {
			width: 100%;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;

			img {
				max-width: 100%;
				max-height: 100%;
				object-fit: contain;
			}
		}

		.image-counter {
			position: absolute;
			top: 10px;
			right: 10px;
			background: rgba(0, 0, 0, 0.5);
			color: white;
			padding: 2px 8px;
			border-radius: 10px;
			font-size: 12px;
			z-index: 2;
		}

		.nav-btn {
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
			width: 32px;
			height: 32px;
			background: rgba(0, 0, 0, 0.5);
			color: white;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
			opacity: 0;
			transition: all 0.3s;
			z-index: 2;

			&.prev-btn {
				left: 10px;
			}

			&.next-btn {
				right: 10px;
			}

			&:hover {
				background: rgba(0, 0, 0, 0.7);
			}
		}

		&:hover {
			.nav-btn {
				opacity: 1;
			}
		}
	}

	.close-btn {
		width: 150px;
		height: 36px;
		background: #edf5ff;
		text-align: center;
		border-radius: 18px;
		color: #0076ff;
		font-size: 16px;
		cursor: pointer;
		transition: all 0.3s;
		margin: 12px auto;
		display: flex;
		align-items: center;
		justify-content: center;

		&:hover {
			background: #dcebff;
		}
	}
}
:deep(.map-type-switch) {
	position: absolute;
	right: 10px;
	bottom: 10px;
	z-index: 100;
	background: white;
	border-radius: 8px;
	box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
	padding: 4px;
	transition: opacity 0.3s ease;

	.map-type-options {
		display: flex;
		gap: 4px;
	}

	.map-type-option {
		position: relative;
		width: 80px;
		height: 60px;
		cursor: pointer;
		border-radius: 4px;
		transition: all 0.3s;
		overflow: hidden;

		.map-icon {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}

		&::after {
			content: attr(data-type);
			position: absolute;
			right: 4px;
			bottom: 4px;
			font-size: 12px;
			color: #666;
			background: rgba(255, 255, 255, 0.9);
			padding: 2px 6px;
			border-radius: 2px;
		}

		&:hover {
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
		}

		&.active {
			box-shadow: 0 0 0 2px #4a85f6;

			&::after {
				color: #4a85f6;
			}
		}
	}
}
</style>
